<template>
  <div class="app-container">
    <tab-selector
      v-model="currentTabSelector"
      :options="tabSelectorOptions"
      @tab-change="handleTabChange"
    ></tab-selector>

    <el-form inline>
      <el-form-item label="预约时间">
        <date-picker
          :value="reservationTime"
          @input="handleReservationTime"
        ></date-picker>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <columns-filter-button></columns-filter-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      border
      :data="personList"
      stripe
      :height="clientHeight"
      :max-height="clientHeight"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleDetails"
      @cell-click="handleCellClick"
      @filter-change="handleFilterChange"
    >
      <el-table-column
        type="index"
        width="55"
        align="center"
        fixed="left"
      ></el-table-column>
      <columns-filter-view>
        <el-table-column
          label="病例号"
          align="center"
          prop="yiyaClinicPerson.caseNumber"
          min-width="150"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view label="头像">
        <el-table-column
          label="头像"
          align="center"
          prop="imageUrl"
          :min-width="'头像'"
        >
          <avatar-image
            slot-scope="scope"
            :patient="scope.row.yiyaClinicPerson"
          ></avatar-image>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="姓名"
          align="center"
          prop="yiyaClinicPerson.name"
          min-width="100"
        >
          <div slot-scope="scope" style="cursor: pointer">
            {{ scope.row.yiyaClinicPerson.name }}
          </div>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="手机号" align="center" min-width="180">
          <hover-phone
            slot-scope="scope"
            :type="1"
            :items="scope.row.yiyaClinicPerson"
          />
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="性别" align="center">
          <template slot-scope="scope">{{
            sexEnum[scope.row.yiyaClinicPerson.sex]
          }}</template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="年龄"
          align="center"
          prop="yiyaClinicPerson.age"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="一级渠道"
          align="center"
          prop="yiyaClinicPerson.channelFirst"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="二级渠道"
          align="center"
          prop="yiyaClinicPerson.channelSecond"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="三级渠道"
          align="center"
          prop="yiyaClinicPerson.channelThird"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="客户状态"
          align="center"
          prop="yiyaClinicPerson.personStatus"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="已交金额"
          align="center"
          prop="yiyaClinicPerson.overMoney"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="欠费"
          align="center"
          prop="yiyaClinicPerson.arrearage"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="TC"
          align="center"
          prop="yiyaAppointment.tcName"
          min-width="100"
          column-key="tcId"
          :filters="tcOptions"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="医生"
          align="center"
          prop="yiyaAppointment.doctorName"
          min-width="100"
          column-key="doctorId"
          :filters="doctorOptions"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="开始时间"
          align="center"
          prop="yiyaAppointment.startReservationTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
              dayjs(scope.row.yiyaAppointment.startReservationTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="结束时间"
          align="center"
          prop="yiyaAppointment.endReservationTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
              dayjs(scope.row.yiyaAppointment.endReservationTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="初诊时间"
          align="center"
          prop="yiyaClinicPerson.firstDiagnoseTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
              scope.row.yiyaClinicPerson.firstDiagnoseTime &&
              dayjs(scope.row.yiyaClinicPerson.firstDiagnoseTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="黄页编号"
          align="center"
          prop="yiyaClinicPerson.yellowCode"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="备注"
          align="center"
          prop="yiyaAppointment.remarks"
          min-width="180"
          :show-overflow-tooltip="true"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="网络咨询师"
          align="center"
          prop="yiyaClinicPerson.networkCounselor"
          min-width="120"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="一级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumFirst"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="二级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumSecond"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="三级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumThird"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>
    <pagination
      v-show="total > 0"
      style="position: fixed; right: 20px; bottom: 20px"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    ></pagination>

    <user-matcher-result
      contains-temp-clinic-person
      @update="getList"
    ></user-matcher-result>
    <user-matcher-appointment @submit="getList"></user-matcher-appointment>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { allListAppointment } from '@/api/services/appointment'
import { listStaff } from '@/api/services/common'
import { encode } from '@/utils/utils'
import {
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getTomorrowStartWithEnd,
  startWithEndMap,
} from '@/utils/date'
import { customerStatusOptions } from '@/utils/options'
import { sexEnum } from '@/utils/enums'

import TabSelector from '@/components/yiya/TabSelector'
import TablePhone from '@/components/yiya/TablePhone'
import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import DatePicker from '@/components/yiya/DatePicker/index'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,
  orderByColumn: 'onClinicTime',
  isAsc: 'desc',
  personStatus: undefined,
  startReservationTime: undefined,
  endReservationTime: undefined,
  channelFirst: undefined,
  channelSecond: undefined,
  channelThird: undefined,
  tcId: undefined,
  doctorId: undefined,
}

export default {
  name: 'ShopQuery',
  components: {
    DatePicker,
    Empty: () => import('@/components/yiya/Empty'),
    UserMatcherResult: () => import('@/components/yiya/UserMatcherResult'),
    UserMatcherAppointment: () =>
      import('@/components/yiya/UserMatcherAppointment'),
    TabSelector,
    HoverPhone: () => import('@/components/yiya/hoverPhone'),
    ColumnsFilterButton,
    ColumnsFilterView,
    AvatarImage: () => import('@/components/yiya/avatarImage'),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 到店患者信息表格数据
      personList: [],
      // 查询参数
      queryParams: {},
      doctorList: [],
      tcList: [],
      reservationTime: [],
      currentTabSelector: ' ',
      clientHeight: document.body.clientHeight - 325,
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
    dayjs() {
      return dayjs
    },
    sexEnum() {
      return sexEnum
    },
    doctorOptions() {
      return this.doctorList.map(({ userName, userId }) => ({
        text: userName,
        value: userId,
      }))
    },
    tcOptions() {
      return this.tcList.map(({ userName, userId }) => ({
        text: userName,
        value: userId,
      }))
    },
    tabSelectorOptions() {
      return [
        {
          label: '总人数',
          value: ' ',
        },
        ...customerStatusOptions.map(({ label, value }) => ({
          label,
          value,
          params: value,
        })),
      ]
    },
  },
  mounted() {
    this.queryParams = {
      ...QUERY_PARAMS,
      ...this.$route.query,
      clinicId: +this.clinicId,
    }
    const today = getTodayStartWithEnd()
    this.handleReservationTime(today)
    this.getDoctorList()
    this.getTcList()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        const { rows, total } = await allListAppointment(this.queryParams)
        this.personList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleDetails(row) {
      this.$router.replace(
        `/shop/details?id=${row.yiyaClinicPerson.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    /**
     * 获取医生列表
     */
    async getDoctorList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: '医生',
      })
      this.doctorList = data
    },
    /**
     * 获取tc列表
     */
    async getTcList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcList = data
    },
    handleFilterChange(e) {
      const [key, value] = Object.entries(e)[0]
      this.queryParams[key] = value.join(',')
      this.handleQuery()
    },
    handleDateButtonKeyChange(type) {
      this.handleReservationTime(startWithEndMap[type])
    },
    handleReservationTime([start, end]) {
      ;[start, end] = [dayjs(start).startOf('day'), dayjs(end).endOf('day')]
      this.reservationTime = [start, end]
      this.queryParams.startReservationTime = start.format(
        'YYYY-MM-DD HH:mm:ss'
      )
      this.queryParams.endReservationTime = end.format('YYYY-MM-DD HH:mm:ss')
      this.handleQuery()
    },
    handleCellClick(row, column) {
      if (column.label === '姓名') {
        this.handleDetails(row)
      }
    },
    handleTabChange({ params }) {
      this.queryParams.personStatus = params
      this.handleQuery()
    },
  },
}
</script>

